package com.service.single.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.single.entity.SystemUser;
import com.service.single.exception.BizException;
import com.service.single.mapper.SystemUserMapper;
import com.service.single.service.SystemUserService;
import com.service.single.util.R;
import com.service.single.util.TokenUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author admin
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {

    @Override
    public R login(String username, String password) {
        QueryWrapper<SystemUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SystemUser systemUser = this.getOne(wrapper);
        if (ObjectUtils.isNotEmpty(systemUser)) {
            String ps = systemUser.getPassword();
            boolean b = BCrypt.checkpw(password, ps);
            if (!b) {
                return R.faild("账号密码不正确");
            }
            if (systemUser.getStatus()) {
                String token = TokenUtil.sign(systemUser, LocalDateTime.now());
                JSONObject jsonObject = new JSONObject();
                LocalDateTime localDateTime = LocalDateTime.now();
                jsonObject.put("loginTime", localDateTime);
                jsonObject.put("username", username);
                jsonObject.put("token", "Bearer " + token);
                jsonObject.put("userId", systemUser.getId());
                systemUser.setLastLogin(localDateTime);
                this.updateById(systemUser);
                return R.success(jsonObject);
            } else {
                return R.faild("该用户已被禁用");
            }
        } else {
            return R.faild("账号密码不正确");
        }
    }

    /**
     * 注册
     *
     * @param user
     */
    @Override
    public R register(SystemUser user) {
        QueryWrapper<SystemUser> wrapper = new QueryWrapper<>();
        String username = user.getUsername();
        wrapper.eq("username", username);
        wrapper.eq(StringUtils.isNotBlank(username), "username", username);

        SystemUser systemUser = this.getOne(wrapper);
        if (ObjectUtils.isNotEmpty(systemUser)) {
            throw new BizException(HttpStatus.BAD_REQUEST.value(), "账号已存在");
        }
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        user.setId(IdUtil.getSnowflakeNextId());
        user.setStatus(true);
        if (this.save(user)) {
            return R.success("注册成功");
        }
        return R.success("注册失败");
    }

}
